<template>
	<view class="u-wrap">
		<template> <!-- v-if="Object.keys(navData).length" -->
			<view class="u-search-box">
				<u-search placeholder="搜索商品" v-model="keyword" @search="searchGoods" @custom="searchGoods" @clear="clearSearch"></u-search>
			</view>
			<view class="u-menu-wrap" >
				<block >
					<view class="">
						<u-dropdown ref="uDropdown" >
							<u-dropdown-item @change="changeCategory" v-model="categoryValue" :title="paramsTitle" :options="categoryOptions"></u-dropdown-item>
							<u-dropdown-item @change="changeChildCategory" v-model="categoryChild" :title="childTitle" :options="childOptions"></u-dropdown-item>
							<u-dropdown-item @change="filtrateChange" v-model="filtrate" :title="filtrateTitle" :options="filtrateOptions"></u-dropdown-item>
						</u-dropdown>
					</view>
					<view class="u-text-center u-m-t-10" >
						<u-tabs 
						:list="sortList" 
						active-color="#fa3534"  
						name="name"
						:is-scroll="false" 
						:current="tabsCurrent"
						@change="changeSort"
						>
						</u-tabs>
					</view>
				</block>
				<block>
					
					<scroll-view scroll-y class="right-box" :class="[sortList.length>0 ? 'right-box1' : 'right-box2']" :style="{height:navHeight+'px'}" :lower-threshold="30" @scrolltolower="toLower">
						
						<view class="u-text-center" v-if="isShowLoading">
							<u-loading color="#82848a"></u-loading>
						</view>
						<template v-else>
							<template v-if="!goodsList.length">
								<u-empty text="暂无商品" mode="list"></u-empty>
							</template>
							<view v-else class="page-view">
								<view class="class-item">
									<view class="item-container">
										<u-row gutter="16" class="u-skeleton">
											<u-col span="6" v-for="book in goodsList">
												<books-card :book="book"></books-card>
											</u-col>
										
										</u-row>
									</view>
									<u-loadmore @loadmore="toLower" :status="loadStatus" icon-color="#82848a"
										color="#82848a" />
								</view>
							</view>
						</template>
					</scroll-view>
				</block>
			</view>
		</template>
		<!-- <template v-else>
			<view class="loading">
				<u-loading size="40" color="#82848a"></u-loading>
				<view>
					<text class="small">拼命加载中~</text>
				</view>
			</view>
		</template> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				categoryValue: 0, // 当前父分类ID
				categoryChild: 0, // 当前子分类ID
				filtrate: 0,//筛选id
				currentFiltrate:0,
				paramsTitle:'分类',
				childTitle:'年级',
				filtrateTitle:'筛选',
				categoryOptions: [],
				childOptions: [],
				filtrateOptions:[
					{
						value:1,
						label:'销量',
						title:'销量',
						
					},{
						value:2,
						label:'价格降序',
						title:'价格↓'
					},{
						value:3,
						label:'价格升序',
						title:'价格↑'
					},],
				activeColor: this.$u.color['error'],
				sortList:[],
				currentSort:0,
				subId:0,
				navData: {},
				goodsList: [],
				scrollTop: 0, //tab标题的滚动条位置
				current: null, // 预设当前项的值
				isShowLoading: false, //加载动画
				keyword: "", //搜索关键词
				page: 1, //当前页数
				loadStatus: "loadmore",
				categoryId: 0,
				selectIndex:0,
				totalPage:0,
				tabsCurrent:0,
				isSerach:false,
				//isNavShow:true
				pH:0, //窗口高度
				navHeight:0, //元素的所需高度
				
			}
		},
		onReady(){
			let that=this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					that._data.pH=res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let titleH=uni.createSelectorQuery().select(".right-box"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data=>{
						let pH=that._data.pH; 
						that._data.navHeight=pH-data.top  //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()
				}
			})
		},
		async onLoad() {
			
			this.getBookCategory()
			this.getGoods()
		},
		methods: {
			// 过滤排序
			filtrateChange(index){
				
				if(this.currentFiltrate==index)return
				
				this.currentFiltrate = index
				for (var i = 0; i < this.filtrateOptions.length; i++) {
					if(this.filtrateOptions[i].value == index){
						this.filtrateTitle = this.filtrateOptions[i].title
					}
				}
				this.clear()
				this.getGoods()
			},
			// 通过用户选择获取商品
			async getGoods(){
				
				const params = {
					//当前页数
					pageNum:this.page
				}
				//是否有父id  小学  初中  高中
				if(this.categoryValue != 0){
					params.cateId = this.categoryValue
				}
				//是否有子id  一年级 二年级 三年级
				if(this.categoryChild != 0){
					params.cateId = this.categoryChild
					params.subId = this.subId
				}
				if(this.subId != 0){
					params.subId = this.subId
				}
				
				//判断是否有搜索关键字
				if(!this.$u.test.isEmpty(this.keyword) && this.isSerach==true){

					params.keyword = this.keyword
				}
				if(this.filtrate == 1){
					//按照销量排序
					params.sort = "sale"
						
						
				}else if(this.filtrate == 2){
					//按照价格降序
					params.sort = "price"
					params.order = 0
					
					
				}else if(this.filtrate == 3){
					//按照价格升序
					params.sort = "price"
					params.order = 1
				}
				console.log(params)
				const res = await this.$u.api.getGoodsList(params)
				console.log("list长度"+res.list.length)
				if(res.list.length>0){
					this.goodsList = [...this.goodsList,...res.list]
				}
				
				// this.goodsList.push(...res.list)
				this.totalPage = res.totalPage
				
				
				if(res.list.length > 0 && !this.$u.test.isEmpty(this.keyword)){
					this.$u.toast("为您筛选出：" + this.keyword)
				}else if(!this.$u.test.isEmpty(this.keyword) && res.list.length == 0){
					this.$u.toast("没有找到商品哟")
				}
				this.isShowLoading = false
			},
			// 切换父分类
			async changeCategory(index) {
				if (index == this.current) return;
				// 先初始化页数和加载状态
				this.categoryChild = 0
				this.current = index;
				this.clear()
				// this.$u.toast(`点击了第${index}项`);
				this.childOptions = []
				this.categoryChild = 0;
				this.sortList = []
				this.childTitle = "年级"
				this.subId = 0
				let res = {}
				for (var i = 0; i < this.categoryOptions.length; i++) {
					if(this.categoryOptions[i].value == index){
						res = this.categoryOptions[i]
					}
				}
				this.paramsTitle = res.name
				this.categoryValue = res.id
				
				if(res.children){
					for(let j=0; j < res.children.length ; j++){
						this.childOptions.push(res.children[j])
						this.childOptions[j].value = res.children[j].id
						this.childOptions[j].label = res.children[j].name
					}
				}
				// 切换分类获取数据
				this.getGoods()

			},
			// 切换子分类
			async changeChildCategory(index) {
				 if (index == this.current) return;
				// 先初始化页数和加载状态
				this.subId = 0
				this.current = index;
				this.clear()
				//this.$u.toast(`点击了第${index}项`);
				let res = {}
				for (var i = 0; i < this.childOptions.length; i++) {
					if(this.childOptions[i].value == index){
						res = this.childOptions[i]
					}
				}
				
				this.childTitle = res.name
				this.categoryChild = res.id
				const subject = await this.$u.api.getCateWithSub(this.categoryChild)
				
				this.sortList = subject
				this.currentSort = this.sortList[0]
				this.subId = this.sortList[0].id
				this.tabsCurrent = 0
				this.getGoods()
				
			},
			//  切换科目
			changeSort(index){
				// console.log(index)
				// console.log(this.sortList[index])  // 这里可以取到科目的id
				
				this.tabsCurrent = index
				this.currentSort = this.sortList[index]
				console.log(this.currentSort.id)
				this.subId = this.currentSort.id
				//索引切换 按不同条件加载
				this.clear()
				
				this.getGoods()

			},
			// 获取商品数据
			async getBookCategory() {
				// this.isShowLoading = true
				const bookCategory = await this.$u.api.bookCategory()
				
				for(let i=0; i < bookCategory.length ; i++){
					this.categoryOptions.push( bookCategory[i])
					this.categoryOptions[i].value = bookCategory[i].id
					this.categoryOptions[i].label = bookCategory[i].name
				}

			},
			// 搜索商品数据
			searchGoods() {
				this.clear()
				// this.categoryValue = 0
				// this.categoryChild = 0
				
				this.isSerach = true
				// 先初始化页数和加载状态
				this.getGoods()
				// this.isSerach = false
				//this.isNavShow = false
				
			},
			// 搜索清空
			clearSearch(){
				this.clear()
				this.categoryValue = 0
				this.categoryChild = 0
				this.paramsTitle = '分类'
				this.childTitle = '年级'
				this.filtrate = 0
				this.filtrateTitle='筛选'
				this.sortList = []
				this.subId=0
				this.keyword = ''
				this.isSerach = false
				// 先初始化页数和加载状态
				this.getGoods()
				//this.isNavShow = true
			},
			
			// 触底加载更多
			async toLower(e) {
				// 如果没有到底，就一直可以触发
				if(this.page >= this.totalPage){
					this.loadStatus = "nomore"
					return
				}
			
				this.loadStatus = "loading"
				this.page++
				this.getGoods()
				
				this.loadStatus = "loadmore"
					
				

			},
			clear(){
				this.page = 1
				this.goodsList = []
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
		/* #ifdef H5*/
		height: calc(100vh - var(--window-top) - 100rpx);
		/* #endif*/
		/* #ifndef H5*/
		height: 100vh;
		/* #endif*/
		// display: flex;
		// flex-direction: column;
		.loading{
			text-align: center;
			position: absolute;
			top: 50%;
			left:50%;
			transform:translate(-50%,-50%);
		}
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		
		// flex: 1;
		// display: flex;
		overflow: hidden;

		.navTitle {
			width: 100%;
			padding: 10rpx;
			font-weight: 550;
			background-color: #fa3534;
			color: #fff;
		}
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.right-box1 {
		
		background-color: rgb(250, 250, 250);
		// height: 880rpx;
		// margin-bottom: 10rpx;
	}
	.right-box2 {
		
		background-color: rgb(250, 250, 250);
		// height: 957rpx;
		// margin-bottom: 10rpx;
	}

	.page-view {
		padding: 16rpx;
	}

	.class-item {
		/* #ifdef H5*/
		height: 80vh;
		/* #endif*/
		/* #ifndef H5*/
		height: 90vh;
		/* #endif*/
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.item-title {
		font-size: 26rpx;
		color: $u-main-color;
		font-weight: bold;
	}

	.item-menu-name {
		font-weight: bold;
		font-size: 26rpx;
		color: $u-main-color;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
	}

	.thumb-box {
		width: 45%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
	}
</style>
